package com.crm.controller.saling;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.crm.pojo.Pay;
import com.crm.pojo.PlaningPay;
import com.crm.service.saling.PayService;
import com.crm.service.saling.PlaningPayService;
import com.crm.vo.PlaningPayClientContractUserInfoVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by dr5hx on 2018/9/3
 */
@Controller
public class PlaningPayController {
    @Autowired
    private PlaningPayService planingPayService;
    @Autowired
    private PayService payService;

    @GetMapping("toPlaningPayList")
    public String toPlaningPayList() {
        return "saling/planingPayList";
    }

    @PostMapping("getPlaningPayList")
    @ResponseBody
    public Map getPlaningPayList(int page, int rows) {
        try {
            List<PlaningPayClientContractUserInfoVO> list = planingPayService.getPlaningPayClientContractUserInfoVOList(page, rows);
            Long count = planingPayService.getPlaningPayListCount();
            Map map = new HashMap();
            map.put("rows", list);
            map.put("total", count);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }


    @PostMapping("setPlaningPayMoneyAlreadyPay")
    @ResponseBody
    public Boolean setPlaningPayMoneyAlreadyBack(Long planingPayId, String rows) {
        try {
            if (planingPayId != null && rows != null) {
                planingPayId = planingPayId == null ? 0 : planingPayId;
                JSONObject jsonObject = JSON.parseObject(rows);
                Pay pay = new Pay();
                pay.setPayIsDel("否");
                PlaningPay planingPay = planingPayService.findOne(planingPayId);
                pay.setPayMoney(planingPay.getPlaningPayMoney());
                pay.setFkPayEmpno(planingPay.getFkPlaningPayEmpno());
                pay.setPayDate(new Date());
                pay.setFkPayPlaningPayId(new BigDecimal(jsonObject.get("planingPayId").toString()));
                if (planingPay.getPlaningPayState().equals("未完成")) {
                    payService.save(pay);
                    planingPay.setPlaningPayState("完成");
                    planingPayService.save(planingPay);
                    return true;
                } else {
                    return false;
                }
            } else {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

}
